package com.qyhl.webtv.commonlib.utils.view.video.onlyprogressvideo;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.commonlib.R;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.utils.view.video.listener.SampleListener;
import com.qyhl.webtv.commonlib.utils.view.video.view.ProgressWheel;
import com.qyhl.webtv.commonlib.utils.view.video.view.VideoGestureView;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.NetworkUtils;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;

import java.util.HashMap;

@Route(path = ARouterPathConstant.VIDEO_ONLY_PROGRESS)
public class OnlyProgressVideoActivity extends AppCompatActivity {
    public final static String IntentKey_VideoUrl = "IntentKey_VideoUrl";
    public final static String IntentKey_VideoCover = "IntentKey_VideoCover";

    OnlyProgressVideo videoPlayer;

    FrameLayout mBackground;

    RelativeLayout rootLayout;

    VideoGestureView videoGestureView;

    ProgressWheel progressWheel;

    OrientationUtils orientationUtils;

    /**
     * 播放地址
     */
    String url = "";
    String videoCover = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setWindowFullScreen();//设置全屏
        setContentView(R.layout.activity_only_progress);
        initIntent();

        initView();

        setListener();

        initData();

    }

    private void initIntent() {
        url = getIntent().getStringExtra(IntentKey_VideoUrl);
        if (url == null) {
            url = "";
        }
        videoCover = getIntent().getStringExtra(IntentKey_VideoCover);
    }

    private void initView() {
        videoPlayer = (OnlyProgressVideo) findViewById(R.id.video_player);
        mBackground = (FrameLayout) findViewById(R.id.video_rl_bg);
        rootLayout = (RelativeLayout) findViewById(R.id.root_layout);
        videoGestureView = (VideoGestureView) findViewById(R.id.video_gesture);
        progressWheel = (ProgressWheel) findViewById(R.id.progress_wheel);
    }

    private void initData() {
        ImageView imageView = new ImageView(this);

        if (videoCover == null || videoCover.length() == 0) {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(url, new HashMap<String, String>());
            Bitmap bitmap = retriever.getFrameAtTime();

            Glide.with(this)
                    .load(bitmap)
                    .apply(new RequestOptions())
                    .into(imageView);
            videoPlayer.setThumbImageView(imageView);
        } else {
            Glide.with(this)
                    .load(videoCover)
                    .apply(new RequestOptions())
                    .into(imageView);

        }
        videoPlayer.setThumbImageView(imageView);
        videoPlayer.setRotateViewAuto(false);
        videoPlayer.setLockLand(true);
        videoPlayer.getBackButton().setOnClickListener(v -> {
            if ( GSYVideoManager.backFromWindowFull(OnlyProgressVideoActivity.this)) {

            } else {
                finish();
            }
        });
        videoPlayer.getFullscreenButton().setOnClickListener(v -> {
            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            videoPlayer.startWindowFullscreen(OnlyProgressVideoActivity.this, false, false);
        });

        videoPlayer.setUp(url, true, "");
        if (NetUtil.isWifi(this)) {
            videoPlayer.startPlayLogic();
        } else {
            showWifiDialog();
        }

    }

    /**
     * wifi判断
     */
    protected void showWifiDialog() {
        if (!NetworkUtils.isAvailable(this)) {
            Toast.makeText(this, getResources().getString(com.shuyu.gsyvideoplayer.R.string.no_net), Toast.LENGTH_LONG).show();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getResources().getString(com.shuyu.gsyvideoplayer.R.string.tips_not_wifi));
        builder.setPositiveButton(getResources().getString(com.shuyu.gsyvideoplayer.R.string.tips_not_wifi_confirm), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                videoPlayer.startPlayLogic();
            }
        });
        builder.setNegativeButton(getResources().getString(com.shuyu.gsyvideoplayer.R.string.tips_not_wifi_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finishActicity();
            }
        });
        builder.create().show();
    }

    /**
     * 设置监听
     */
    private void setListener() {
        rootLayout.setOnClickListener(v -> finishActicity());

        videoGestureView.setOnSwipeListener(new VideoGestureView.OnSwipeListener() {
            @Override
            public void downSwipe() {
                finishActicity();
            }

            @Override
            public void onSwiping(float deltaY) {

                float mAlpha = 1 - deltaY / 500;
                if (mAlpha < 0.3) {
                    mAlpha = 0.3f;
                }
                if (mAlpha > 1) {
                    mAlpha = 1;
                }
                mBackground.setAlpha(mAlpha);
            }

            @Override
            public void overSwipe() {
                mBackground.setAlpha(1);
            }
        });

        videoPlayer.setVideoAllCallBack(new SampleListener(new SampleListener.CallbackInterface() {
            @Override
            public void prepareCallBack(boolean isPrepared) {
                if (isPrepared) {
                    progressWheel.setVisibility(View.GONE);
                } else {
                    progressWheel.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void autoComplete() {
                finishActicity();
            }

        }));

    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
    }

    @Override
    public void onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }



    /**
     * 设置全屏
     */
    private void setWindowFullScreen() {
        //设置全屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (Build.VERSION.SDK_INT >= 19) {
            // 虚拟导航栏透明
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    /**
     * 结束activity
     */
    private void finishActicity() {
        mBackground.setAlpha(0);
        finish();
        this.overridePendingTransition(0, R.anim.video_emptycontrol_exit_anim);
    }
}
